package com.yc.dygang;

import com.yc.dygang.entity.Movie;
import com.yc.dygang.mapper.MovieMapper;
import com.yc.dygang.util.MyBatisHelper;
import org.apache.ibatis.session.SqlSession;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Timer;
import java.util.TimerTask;

public class Spider {

    public static void main(String[] args) throws IOException {
        capture();
    }

    public static void capture() throws IOException {
        Movie movie = new Movie();
        URL url = new URL("https://www.dygang.cc/");
        Document document = Jsoup.parse(url,10000);
        Elements elements = document.select("[id^=tab1_div_] td[width='132']");

        elements.forEach(element -> {
            Elements a = element.select("table:nth-child(1) a");
            String href = a.attr("href");
            String type = href.replaceAll("/(\\w+)/.*", "$1");
        //    String intime = href.replaceAll("/(\\w+)/(\\d+)/.*", "$2");
            String id = href.replaceAll("/(\\w+)/(\\d+)/(\\d+).*", "$3");
            Element img = element.selectFirst("table:nth-child(1) a>img");
            String image = img.attr("src");
            String name = img.attr("alt");
            Elements td = element.select("table:nth-child(3) td");
            String intime = td.text();
            //System.out.printf("%s ,%s, %s, %s, %s\n", id, name, type , intime, image);

            movie.setId(Integer.valueOf(id));
            movie.setIntime(intime);
            movie.setType(type);
            movie.setImage(image);
            movie.setName(name);


            try(SqlSession session = MyBatisHelper.getSession()){
                MovieMapper mapper = session.getMapper(MovieMapper.class);
                String selectMovie = mapper.selectMovie(movie.getId());
                if (selectMovie == null){
                    mapper.insertMovie(movie);
                    System.out.println("已将《" + movie.getName() + "》存入数据库");
                }else{
                    System.out.println("已存在《" + movie.getName() + "》 id:" + movie.getId());
                }
                session.commit();
            }



        });
    }
}
